package com.starblink.imgsearch.camera

import android.net.Uri
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import com.starblink.android.basic.extension.navigationTo
import com.starblink.basic.ext.nowTime
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.imgsearch.camera.ui.CameraTVMActivity
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File

/**相机拍照管理器*/
class ImageCapturer(val mActivity: CameraTVMActivity) {
    companion object {
        private const val TAG = "ImageCapturer"
    }

    private val camConfig = mActivity.camConfig

    /**拍照照片保存路径*/
    private val defaultFileOutPath get() = "${mActivity.externalCacheDir}/img_search_tmp.jpeg"

    public var now = 0L

    /**拍照*/
    fun takePicture() {
        if (camConfig.camera == null) {
            return
        }

        // 记录拍照时间
        now = nowTime()

        val outputOptions =
            ImageCapture.OutputFileOptions.Builder(File(defaultFileOutPath)).build()

        camConfig.imageCapture!!.takePicture(
            outputOptions, camConfig.cameraExecutor, object : ImageCapture.OnImageSavedCallback {
                override fun onError(exc: ImageCaptureException) {
                    SKLogger.e(CameraTVMActivity.TAG, "Photo capture failed: ${exc.message}")
                    enableCaptureButton()
                }

                override fun onImageSaved(output: ImageCapture.OutputFileResults) {
                    output.savedUri?.let { compressAndToResult(it) }
                }
            })

        disableCaptureButton()
    }

    /**压缩图片，跳转结果页*/
    public fun compressAndToResult(uri: Uri) {
        Luban.with(mActivity).ignoreBy(0).load(uri)
            .setCompressListener(object : OnCompressListener {
                override fun onStart() {

                }

                override fun onSuccess(index: Int, file: File) {
                    SKLogger.d(
                        TAG,
                        "compress success -->> ${file.path}, spent time: ${nowTime() - now}ms"
                    )
                    enableCaptureButton()
                    goToImgSearchResult(file.path)
                }

                override fun onError(index: Int, e: Throwable) {
                    e.printStackTrace()
                    SKLogger.wtf(
                        TAG,
                        "luban compress error -->> spent: ${nowTime() - now}ms",
                        e
                    )
                    enableCaptureButton()
                    goToImgSearchResult(uri.toString())
                }
            }).launch()
    }

    /**跳转图搜结果页*/
    private fun goToImgSearchResult(path: String) {
        mActivity.navigationTo(RoutePage.ImageSearch.PAGE_RESULT) {
            withString("file_path", path)
        }
    }

    private fun disableCaptureButton() {
        mActivity.captureButton.isEnabled = false
    }

    private fun enableCaptureButton() {
        mActivity.captureButton.isEnabled = true
    }
}
